#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <string.h>
#include "service.h"
#include "utils.h"
#include "MCP23017.h"

osEventFlagsId_t service_EvtID;
osThreadAttr_t service_Attr;

int service_ReadUartLength;
int service_UartLength;

uint8_t service_uartData[300];
uint8_t * service_uartDataPtr;

void Service_sendOSEvent(void){
    osEventFlagsSet(service_EvtID, SERVICE_FLAGS_MSK1);
    osThreadYield();
}

// 业务处理线程
static void * service_Task(const char *arg){
    (void)arg;

    mm_LogPrint("[HMNetDTU]NetDTU service Task start....\r\n");

    while(1){
        osEventFlagsClear(service_EvtID,SERVICE_FLAGS_MSK1);
        osEventFlagsWait(service_EvtID, SERVICE_FLAGS_MSK1, osFlagsWaitAny, 500);
        if(service_ReadUartLength != 0){
            service_UartLength = service_ReadUartLength;
            service_ReadUartLength = 0;
            mm_LogPrint("[HMDTU_service]uart2 get Data length:%d\r\n",service_UartLength);

            // 通过Modbus写IO
            if(service_uartData[0] == 0x01 && service_uartData[1] == 0x06){            // 1号地址写IO
                MCP23017_WRITE_GPIO(0x00,MCP23017_PORTB,service_uartData[5]);
                IoTUartWrite(2, service_uartDataPtr, service_UartLength);
            }else if(service_uartData[0] == 0x01 && service_uartData[1] == 0x03){      // 1号地址读IO
                // MCP23017_WRITE_GPIO(0x00,MCP23017_PORTB,service_uartData[5]);
            }

        }

        memset(service_uartData,0,300);
    }

    return NULL;
}

void service_init(void){
    service_Attr.name = "service_Task";
    service_Attr.attr_bits = 0U;
    service_Attr.cb_mem = NULL;
    service_Attr.cb_size = 0U;
    service_Attr.stack_mem = NULL;
    service_Attr.stack_size = 1024 * 20;
    service_Attr.priority = 25;


    service_uartDataPtr = service_uartData;

    if (osThreadNew((osThreadFunc_t)service_Task, NULL, &service_Attr) == NULL) {
        mm_LogPrint("[HMNetDTU] Falied to create service_Task!\n");
    }
    service_ReadUartLength = 0;
    service_EvtID = osEventFlagsNew(NULL);
}